<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
require_once '../../model/users.php';
require_once '../../model/email.php';
include_once("../../model/trade.php");
include_once("../../model/budget.php");
require_once "../../includes/classes/paging_htacess.php";
require_once '../../redirect.php';
require_once '../../model/admindetails.php';
include_once '../../model/email.php';


## creating objects of required models
$userObj 		= new Model_Users();
$tradeObj = new Model_TRADE();
$budgetObj = new Model_Budget();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();



checkUserLogin();


if($_SESSION['user_type'] == '3')
{
	@header("location:".SITE_URL."/");
	exit;
}



$userId =$_SESSION['getbids_id'];

## When user wants to delete the job
if($_GET['id1'] == 'delete' && $_GET['id2']!='')
{
	$LeadsID = base64_decode($_GET['id2']);
	$userObj->deleteLeadById($LeadsID);
	$_SESSION['msg'] = "<div class='success_msg'style='margin-top:5px;margin-bottom: 20px;'><span>Leads deleted successfully !</span></div>";
	header("Location:".SITE_URL."/leads/myleads");
	exit;
}

## When user wants to request rating
if($_GET['id1'] == 'rating' && $_GET['id2']!='')
{
	$LeadsID = base64_decode($_GET['id2']);
	$jobdetail = $userObj->getUserViewjobDetailsByID($LeadsID);
	
	$getuserjobdetail = $userObj->getJobDetailsById($jobdetail['jobid']);
	
	$jobtype = $tradeObj->getTradeCategoryDetailsById($getuserjobdetail['jobtype_id']);					
	
	
	// send email message to home owner 
	$email_message = $emailObj->getEmailById(18);
	$e_subject = $email_message['email_subject'];
	$message = $email_message['email_content']; 
	
	$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		

	
	$url = SITE_URL."/jobs/myjobs/";
	
	$message = str_replace('[NAME]', $getuserjobdetail['first_name'].' '.$getuserjobdetail['last_name'] , $message);
	$message = str_replace('[TRADE_NAME]', $_SESSION['first_name'].' '.$_SESSION['last_name'] , $message);
	$message = str_replace('[JOBID]', "#PR".trim($getuserjobdetail["postjob_id"]), $message); 
	$message = str_replace('[TRADE]', trim($getuserjobdetail["trade_category"]), $message);
	$message = str_replace('[JOBTYPE]', trim($jobtype["trade_category"]), $message); 
	$message = str_replace('[JOBDESC]', trim($getuserjobdetail["job_desc"]), $message); 
	$message = str_replace('[URL]', $url, $message); 
	$message = str_replace('[SITENAME]', SITENAME, $message);
	
	
	
	$to= trim($getuserjobdetail["email"]);
	$adminEmail = $adminObj->getAdminDetails();
	$from = $_SESSION['email'];
	$fromname= $_SESSION['first_name'].' '.$_SESSION['last_name'];
					 
	$emailTemplate = file_get_contents('../../emailtemplate.html');
	$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
	$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
	$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
	//echo $template_msg; exit;
	if(trim($to) != '')
	@send_mail($to, $template_msg, $subject, $from, $fromname); 
	
	//message add for inbox homeowner
		$msgAddArray = array();
		$msgAddArray['from_id']   = '1'; 
		$msgAddArray['to_id'] 	  = $getuserjobdetail['user_id'];
		$msgAddArray['ad_id']     = $postjobid;
		$msgAddArray['subject']   = $subject;
		$msgAddArray['message']   = $message;
		$msgAddArray['send_date'] = getCurDate();
		$msgAddArray['label'] 	  = 'inbox';
		$msgObj->addMessage($msgAddArray); # add record for inbox
		
		$msgAddArray['label'] 	  = 'outbox';
		$msgObj->addMessage($msgAddArray); # add record for outbox
	
	
	$_SESSION['msg'] = "<div class='success_msg'style='margin-top:5px;margin-bottom: 20px;'><span>Request sent successfully !</span></div>";
	header("Location:".SITE_URL."/leads/myleads");
	exit;
}




## for pagination
	$page = $_GET['id1'];
	if(!isset($_GET['id1']))
	$page = 1;
	else
	$page = $page;
	
## limit per pag 
$tetsimonialPerPage =10;
$StartRow = $tetsimonialPerPage  * ($page-1);
## Getting all leads from database according to user

if($_POST['jobtype']!='0' && $_POST['jobtype']!='')
{
	$jobtype = $_POST['jobtype']; 
} 
elseif($_GET['id2']!='' && $_GET['id2']!='JOBTYPE')
{
	$jobtype =$_GET['id2']; 
}
else {
	$jobtype = '';
}
if($_POST['budget']!='0' && $_POST['budget']!=''){
	$budget = $_POST['budget'];
} 
elseif($_GET['id3']!='' && $_GET['id3']!='BUDGET')
{
	$budget =$_GET['id3']; 
}
else 
{
	$budget = '';
}
if($_POST['project_status']!='0' && $_POST['project_status']!=''){
	$Projectstatus = $_POST['project_status']; 
}
elseif($_GET['id4']!='' && $_GET['id4']!='PROJECTSTAUS')
{
	$Projectstatus =$_GET['id4']; 
}
else {
	$Projectstatus = '';
}


$leadsArray  = $userObj->leadsAccordingToUserId($userId,$jobtype,$budget,$Projectstatus,'','',false);
$totalCount        = count($leadsArray);
$smarty -> assign("recordsFound",$totalCount);

$result = $userObj->leadsAccordingToUserId($userId,$jobtype,$budget,$Projectstatus,$tetsimonialPerPage,$StartRow,true);
$show = 1;
$total_pages = ceil($totalCount / $tetsimonialPerPage);
	if($total_pages > 1)
	$smarty -> assign("showpgnation","yes");
	$showing    = !isset($_GET["id1"]) ? 1 : $page;
	
	## it shoould be file name 
	if(($_GET['id2']!='' || $_GET['id3']!='' || $_GET['id4']!='') || ($_POST['jobtype']!='' || $_POST['budget']!='' || $_POST['project_status']!=''))
	{
		$firstlink ='';
		if(($_POST['jobtype']!='0' || $_GET['id2']!='' )&& $_GET['id2']!='JOBTYPE')
			$firstlink  .= $jobtype."/";
		else	
			$firstlink  .= "JOBTYPE/";
			
		if(($_POST['budget']!='0' || $_GET['id3']!='' )&& $_GET['id3']!='BUDGET')
			$firstlink  .= $budget."/";
		else	
			$firstlink  .= "BUDGET/";

		if(($_POST['project_status']!='0' || $_GET['id4']!='') && $_GET['id4']!='PROJECTSTAUS')
			$firstlink  .= $Projectstatus."/";
		else	
			$firstlink  .= "PROJECTSTAUS/";
			
		
		$firstlink .= "myleads/";	
	}
	else
		$firstlink  = "myleads/";
	
	$baselink   = $firstlink; 
	if($total_pages!=0)
		$pagenation = pagination($total_pages, $show, $showing, $firstlink, $baselink, "", "leads");
	$smarty -> assign("pagenation", $pagenation);
	$smarty -> assign("page", $page);
	//
	
	for($i=0;$i<count($result);$i++)
	{
		if($result[$i]['trade_id']!='')
		{
			$gettradedetail = $tradeObj->getTradeCategoryDetailsById($result[$i]['trade_id']);
			$result[$i]['tradename'] = $gettradedetail['trade_category'];
		}
		
		if($result[$i]['jobtype_id']!='')
		{
			$getjobtypedetail = $tradeObj->getTradeCategoryDetailsById($result[$i]['jobtype_id']);
			$result[$i]['jobtypename'] = $getjobtypedetail['trade_category'];
		}
		
		if($result[$i]['approx_budget']!='')
		{
			$getbudgetdetail = $budgetObj->getBudgetDetailsById($result[$i]['approx_budget']);
			$result[$i]['budgetname'] = $getbudgetdetail['budget_name'];
		}	
		
		if($result[$i]['jobid']!='')
		{
			$getuserreviewdet  = $userObj->getReviewdetailByFromToUIDAndJobID($result[$i]['jobid'],$result[$i]['userid']);
			if($getuserreviewdet['id']!='')
			{
				$result[$i]['reviewid'] = $getuserreviewdet['id'];
				$result[$i]['getreview'] = 'yes';
			}
			else
			{
				$result[$i]['getreview'] = 'no';	
			}
			
		}		
		
	}
	//echo "<pre>"; print_r($result);exit;
	$smarty->assign("leadsArray", $result);
	
/*===========================================================================*/
	$userDetArray = $userObj->getUserDetailsByUserId($userId);
	$smarty->assign("userDetArray", $userDetArray);	
	
/*===========================================================================*/	

$getallTradeJobType = $tradeObj->getAllJobTypeWithActiveStatus();
$smarty->assign("getallTradeJobType", $getallTradeJobType);	

$getallBudget = $budgetObj->getAllBudgetWithActiveStatus();
$smarty->assign("getallBudget", $getallBudget);	


if($_SESSION['msg']){
		$smarty->assign("msg", $_SESSION['msg']);
		unset($_SESSION['msg']);
}

$active ="myaccount";
$smarty->assign('active',$active);
$subactive ="myleads";
$smarty->assign('subactive',$subactive);
$smarty->assign('mainmenu',"4");

$smarty->display(TEMPLATEDIR.'/modules/leads/myleads.tpl');
unset($smarty);
?>
